package vikaa.ui;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;

import org.json.JSONObject;

import vikaa.bean.File_item;
import vikaa.framework.AppContext;
import vikaa.timelinepackage.TimelineGallery;
import vikaa.tools.HttpUtil;
import vikaa.tools.ImageUtils;
import vikaa.wowo.R;
import vikaa.wowo.cache.AuthoSharePreference;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.view.KeyEvent;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;


public class ChoosePhotoUpload extends Activity{
	private static final int ACCESS_SUSSESS = 1;
	private static final int ACCESS_FAIL = 0;
	private String sid;
	private ArrayList<String> pathlist;
	private ProgressBar pb;
	private TextView pbstateTv;
	private TextView uploatTv1;
	private TextView uploatTv2;
	private long exitTime = 0;
	private BlockingQueue<String> pathQueue;
	private upFileThread upThread; 
	public static ArrayList<File_item> uplist ;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.photolist_upload);
		uplist = new ArrayList<File_item>();
		Intent intent = getIntent();
		Bundle b = intent.getExtras();
		sid = b.getString("sid");
		pathlist = b.getStringArrayList("pathlist");
		initview();
		pb.setMax(pathlist.size());
		pbstateTv.setText("共图片"+pathlist.size()+"张");
		pb.setClickable(false);
		pathQueue = new ArrayBlockingQueue<String>(pathlist.size());
		for(int i=0;i<pathlist.size();i++){
			try {
				//new upFileThread().start();
				pathQueue.put(pathlist.get(i));
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		upThread =  new upFileThread(pathQueue.poll());
		upThread.start();
	}
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if((keyCode == KeyEvent.KEYCODE_BACK || keyCode == KeyEvent.KEYCODE_HOME)&& event.getAction() == KeyEvent.ACTION_DOWN ){     
	        if((System.currentTimeMillis()- exitTime) > 2000){    
	            Toast.makeText(getApplicationContext(), getString(R.string.upload_toast), Toast.LENGTH_SHORT).show();                                  
	            exitTime = System.currentTimeMillis();     
	        } else {  
	            finish();  
	        }  
	        return true;     
	    }  
	    return super.onKeyDown(keyCode, event);  
	}
	@Override
	protected Dialog onCreateDialog(int id) {
		// TODO Auto-generated method stub
		switch(id){
		case 1:
			return new AlertDialog.Builder(this)
			.setTitle(getString(R.string.operation_complete))
			.setPositiveButton(R.string.back, new DialogInterface.OnClickListener(){
				public void onClick(DialogInterface dialog, int which) {
					  finish(); 
					  TimelineGallery.isrefresh = true;
				}
			}).create();
		default:
			return null;
		}
	}
	private void initview() {
		pb = (ProgressBar)findViewById(R.id.uploadPb);
		uploatTv1 = (TextView)findViewById(R.id.upload_photo_Tv1);
		uploatTv2 = (TextView)findViewById(R.id.upload_photo_Tv2);
		pbstateTv = (TextView)findViewById(R.id.pbstateTv);
	}
	
	Handler mhandler = new Handler(){
		int i=0;
		public void handleMessage(android.os.Message msg) {
			switch(msg.what){
			case ACCESS_SUSSESS:
				i++;
				pbstateTv.setText("上传第"+i+"张，共"+pathlist.size()+"张");
				pb.setProgress(i);
				if(pathQueue.size()>0){
			    		upThread = new  upFileThread(pathQueue.poll());
			    		upThread.start();
			    	}
				if(pb.getProgress() == pb.getMax()){
					showDialog(1);
				}
				//TODO
				break;
			case ACCESS_FAIL:
				String massage = (String)msg.obj;
				Toast.makeText(getApplicationContext(),	massage, Toast.LENGTH_LONG).show();
				i++;
				pbstateTv.setText("上传第"+i+"张，共"+pathlist.size()+"张");
				pb.setProgress(i);
				if(pathQueue.size()>0){
			    		upThread = new  upFileThread(pathQueue.poll());
			    		upThread.start();
			    }
				if(pb.getProgress() == pb.getMax()){
					showDialog(1);
				}
				break;
			}
		};
	};
	class upFileThread extends Thread{
		private String path;
		private boolean isrun = true;
		public upFileThread(String path) {
			super();
			this.path = path;
		}
		
		public String getPath() {
			return path;
		}

		public void setPath(String path) {
			this.path = path;
		}

		@Override
		public void run() {
			while(isrun){
				isrun = false;
				Map<String, String> map = new HashMap<String, String>();
				String url = HttpUtil.BASE_URL + "file/upload";
				try {
					String savePath = "";
					String storageState = Environment.getExternalStorageState();		
					if(storageState.equals(Environment.MEDIA_MOUNTED)){
						savePath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/vikaa/upload/";
						File savedir = new File(savePath);
						if (!savedir.exists()) {
							savedir.mkdirs();
						}
					}
					File file = null;
					try{
						file = new File(path);
					}catch(Exception e){
						finish();
					}
					String prefix =  file.getName();
					File fileO = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/vikaa/upload/" + prefix);
					if(fileO.exists()){
						path = Environment.getExternalStorageDirectory().getAbsolutePath() + "/vikaa/upload/" + prefix;
					}else{
						Bitmap bitmap= ImageUtils.getBitmapByPath(path, (new AppContext().getDisplayWidth(ChoosePhotoUpload.this)));
						try {
							ImageUtils.saveImageToSD(Environment.getExternalStorageDirectory().getAbsolutePath() + "/vikaa/upload/" + prefix, bitmap, 100);
							path = Environment.getExternalStorageDirectory().getAbsolutePath() + "/vikaa/upload/" + prefix;
						} catch (IOException e) {
							e.printStackTrace();
						}
					}
					String phpSESSID = AuthoSharePreference.getCookie(ChoosePhotoUpload.this);
					map.put("space_id", sid);
					map.put("PHPSESSID", phpSESSID);
					Map<String, File> map2 = new HashMap<String, File>();
					map2.put("Filedata",new File(path));
					JSONObject jsonObj = new JSONObject(HttpUtil.postFileRequest(url, map, path));
					if(jsonObj.getString("result").equals("1")){
						File_item item = new File_item();
						item.setDateline(jsonObj.getJSONObject("info").getString("dateline"));
						item.setFile_id(jsonObj.getJSONObject("info").getString("file_id"));
						item.setHash(jsonObj.getJSONObject("info").getString("hash"));
						item.setSelected(false);
						item.setThumbnail(jsonObj.getJSONObject("info").getString("thumbnail"));
						item.setUploaded(false);
						uplist.add(item);
						Message msg = mhandler.obtainMessage(ACCESS_SUSSESS);
						msg.sendToTarget();
					}
					else{
						Message msg = mhandler.obtainMessage(ACCESS_FAIL);
						msg.obj = jsonObj.getString("msg");
						msg.sendToTarget();
					}
				}catch (Exception e) {
					e.printStackTrace();
				}
			}
		}
	}
}
